package org.ah.ai.util;
import java.io.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
// Eclipse中不能使用BASE64Decoder，需要设置
// https://blog.csdn.net/u011514810/article/details/72725398
public class ImgUtil {
	// Base64解码
	public static boolean decodeImg(String imgCode, String imgFilePath) {
		if (imgCode == null || imgCode.isEmpty()) {
			return false;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgCode);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					// 调整异常数据
					b[i] += 256;
				}
			}
			// 新图片
			OutputStream os = new FileOutputStream(imgFilePath);
			os.write(b);
			os.flush();
			os.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	// Base64
	public static String encodeImg(String imgFile) {
		InputStream in = null;
		byte[] bs = null;
		try {
			in = new FileInputStream(imgFile);
			bs = new byte[in.available()];
			in.read(bs);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bs);
	}
}